import { CustomRequestOptions } from '@/interceptors/request'
import { useUserStore } from '@/store/index'

export const http = <T>(options: CustomRequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, reject) => {
    uni.request({
      ...options,
      dataType: 'json',
      // #ifndef MP-WEIXIN
      responseType: 'json',
      // #endif
      // 响应成功
      success({ data: res }) {
        // 状态码 2xx，参考 axios 的设计
        if (res.code === 200) {
          // 2.1 提取核心数据 res.data
          resolve(res.data as IResData<T>)
        } else if (res.code === 401) {
          // 401错误  -> 登录失效
          const userStore = useUserStore()

          userStore.clearUserInfo()
          userStore.setShowModal(true)

          reject(res)
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          !options.hideErrorToast &&
            uni.showToast({
              icon: 'none',
              title: (res as IResData<T>).msg || '请求错误',
            })
          reject(res)
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
        })
        reject(err)
      },
    })
  })
}

/**
 * GET 请求
 * @param url 后台地址
 * @param query 请求query参数
 * @returns
 */
export const httpGet = <T>(url: string, query?: Record<string, any>) => {
  return http<T>({
    url,
    query,
    method: 'GET',
  })
}

/**
 * POST 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数，post请求也支持query，很多微信接口都需要
 * @returns
 */
export const httpPost = <T>(
  url: string,
  data?: Record<string, any>,
  query?: Record<string, any>,
) => {
  return http<T>({
    url,
    query,
    data,
    method: 'POST',
  })
}

export function uploadFile(tempFilePath) {
  const userStore = useUserStore()
  const { token } = userStore.userInfo as unknown as IUserInfo

  return new Promise<void>((resolve, reject) => {
    uni.uploadFile({
      url: import.meta.env.VITE_UPLOAD_BASEURL,
      filePath: tempFilePath,
      name: 'file',
      formData: {},
      header: {
        'Content-Type': 'multipart/form-data', // formdata提交格式
        Authorization: `Basic c2FiZXI6c2FiZXJfc2VjcmV0`,
        'Blade-Auth': `bearer ${token}`,
      },
      success: (uploadFileRes) => {
        if (uploadFileRes.statusCode !== 200) {
          uni.showToast({ title: '上传图片失败!', icon: 'error' })
          resolve(
            'http://39.108.7.196:9000/homestay-hotels/upload/20240717/df995d0085494409b8d35a2f0b524b0c.png',
          )
        } else {
          const obj = JSON.parse(uploadFileRes.data)
          resolve(obj.url)
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

http.get = httpGet
http.post = httpPost
http.uploadFile = uploadFile
